<template>
    <div class="filter">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="产品名称">
                <el-input v-model="formInline.user" placeholder="产品名称" clearable />
            </el-form-item>
            <el-form-item label="添加时间">
                <el-date-picker v-model="formInline.date" type="date" placeholder="选择日期" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="toSearch">查询</el-button>
            </el-form-item>
        </el-form>
        <div class="operation">
            <!-- <el-button type="warning"><el-icon><Plus /></el-icon>  添加商品</el-button> -->
            <el-button type="warning" :icon="Plus" @click="addRow">添加商品</el-button>
            <el-button type="danger" :icon="Delete" @click="deleteRow">批量删除</el-button>
        </div>
    </div>
    <div class="content">
        <el-table :data="tableData" border style="width: 100%" header-cell-class-name="active-header"
            cell-class-name="table-center">
            <el-table-column type="selection" width="60" />
            <el-table-column prop="productCode" label="商品编码" width="90" />
            <el-table-column prop="productName" label="商品名称" width="90" />
            <el-table-column prop="productPrice" label="商品价格" width="90" />
            <el-table-column prop="productCate" label="商品类目" width="90" />
            <el-table-column prop="createTime" label="添加时间" width="180">
                <template #default="scope">
                    {{ dayjs(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
                </template>
            </el-table-column>
            <el-table-column prop="productSellingPoint" label="商品卖点" width="90" />
            <el-table-column prop="productDesc" label="商品描述" width="180">
                <template #default="scope">
                    {{ removeHtmlTag(scope.row.productDesc) }}
                </template>
            </el-table-column>
            <el-table-column fixed="right" prop="operation" label="操作" width="180">
                <template #default="scope">
                    <el-button size="small" type="primary" :icon="Edit"
                        @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" :icon="Delete"
                        @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="page">
            <Pagination :pageSize="pageSize" :total="total" @getCurrentPage="getCurrentPage"></Pagination>
        </div>
    </div>
</template>
  
<script setup>
import { reactive, getCurrentInstance, inject, onMounted, ref } from 'vue'
import {
    Delete,
    Edit,
    Plus
} from '@element-plus/icons-vue'
import dayjs from 'dayjs';
import { removeHtmlTag } from '@/utils/common';
import Pagination from '@/components/pagination/Pagination.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import router from '@/router'
import useGoodsInfoStore from '@/stores/goodsInfo'
// import { useRouter } from 'vue-router'
// const router = useRouter()

const store = useGoodsInfoStore();

const formInline = reactive({
    user: '',
    region: '',
    date: '',
})

let pageSize = ref(1);
let total = ref(10);
const currentPage = ref(1);

let tableData = ref([])
// const tableData = ref([
//     {
//         productCode: '1',
//         productName: '苹果',
//         productPrice: '2.0元/斤',
//         productCate: '水果',
//         createTime: '2021-05-01',
//         productSellingPoint: '新鲜水果',
//         productDesc: '新鲜水果',
//         operation: '新增'
//     }, {
//         productCode: '2',
//         productName: '小黄鱼',
//         productPrice: '10.0元/斤',
//         productCate: '水产类',
//         createTime: '2021-05-01',
//         productSellingPoint: '水产类',
//         productDesc: '水产类',
//         operation: '新增'
//     }
// ])
const handleEdit = (index, row) => {
    console.log(index, row)
    store.setGoodsInfo({
        title: '编辑',
        goodsInfo: row,
    });
    console.log('store:', store)
    // 跳转到添加界面 商品添加 编辑 查看详情是同一个界面
    router.push('/product/addProduct')
}
const handleDelete =  async (index, row) => {
    console.log(index, row)
    ElMessageBox.confirm(
        '是否确认删除数据?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        // TODO:调用删除接口
        let res = await api.getProductDeleteById({ id: row.productCode });
        console.log('res:', res)
        ElMessage({
            type: 'success',
            message: '删除成功',
        })
        // 判断当前数据是否是最后一条数据
        if (total.value % pageSize.value === 1){
            currentPage.value = currentPage.value - 1 > 0 ? currentPage.value - 1 : 1;
        }
        getProductList(currentPage.value);
        console.log('currentPage:', currentPage.value)
    }).catch(() => {
        
        ElMessage({
            type: 'info',
            message: '删除取消',
        })
    })
}
// 1. 获取全局变量
// const app = getCurrentInstance()
// console.log('app', app.appContext.config.$api)

// 2.获取全局变量 inject
const api = inject('$api')
console.log('api--->', api)

const toSearch = async () => {
    let res = await api.getProductSearch({ name: formInline.name });
    console.log('res:', res)
    if (res.data.status === 200) {
        tableData.value = res.data.list;
        total.value = Math.ceil(res.data.list.length / pageSize.value);
    } else {
        tableData.value = [];
        total = 0;
        pageSize = 0;
    }
}
// 获取产品列表
const getProductList = async (page) => {
    let res = await api.getProductList({ page })
    console.log('getProductList:', res.data)
    tableData.value = res.data.list
    total.value = res.data.total
    pageSize.value = res.data.pageSize
}
const getCurrentPage = (page) => {
    console.log('page:', page)
    currentPage.value = page;
    getProductList(page);
}

const addRow = () => {
    store.setGoodsInfo({
        title: '新增',
        goodsInfo: {},
    });
    router.push('/product/addProduct')
}

onMounted(() => {
    getProductList()
})
</script>

<style lang="scss" scoped>
.page {
    padding: 10px;
}

.demo-form-inline .el-input {
    --el-input-width: 220px;
}

.demo-form-inline .el-select {
    --el-select-width: 220px;
}

.filter {
    height: 100px;
    background-color: white;
    border: 1px solid rgb(230, 230, 230);
    padding: 10px 10px;
    margin-bottom: 20px;

    .operation {
        padding: 10px 10px;
    }
}

::v-deep .active-header {
    color: black;
    text-align: center;
}

::v-deep .table-center {
    text-align: center;
}
</style>